/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-18 15:18:12
 ******************************************************************************/
package cn.com.xy.sms.sdk.ui.popu.util;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.NinePatch;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Build.VERSION;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.smsmessage.BusinessSmsMessage;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.KeyManager;
import cn.com.xy.sms.sdk.util.StringUtils;

@SuppressLint("NewApi")
public class ViewUtil {

	// public final static String START_PLACE = "start_place";
	// public final static String END_PALCE = "end_place";
	// public final static String AIR_NUM = "air_num";
	// public static final String TABLE_NAME = "tb_air";

	public static void setTextViewValue(TextView view, BusinessSmsMessage message, String key) {
		setTextViewValue(view, message, key, "");
	}

	public static void setTextViewValue(TextView view, BusinessSmsMessage message, String key, String defaultValue) {
		try {
			if (view != null && message != null) {
				String value = (String) message.getValue(key);

				setTextViewValue(view, value == null ? defaultValue : value);

				// if (!StringUtils.isNull(value)) {
				//
				// view.setText(value);
				// } else {
				// if (!StringUtils.isNull(defaultValue)) {
				// view.setText(defaultValue);
				// } else {
				// view.setText("");
				// }
				//
				// }
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "setTextViewValue: ", e);

		}

	}

	/**
	 * （小邱说临时不用，暂留） 超过字数，字体自动缩放
	 * 
	 * @param view
	 *            控件
	 * @param str
	 *            内容
	 * @param maxLength
	 *            允许的最大显示长度
	 * @param textSize
	 *            允许最大的字体大小
	 * @param context
	 *            activity
	 */
	public static void setTextViewValue(TextView view, BusinessSmsMessage message, String key, int maxLength,
			int textSize, String defaultValue, Context context) {

		try {
			if (view != null && message != null) {
				String value = (String) message.getValue(key);

				if (!StringUtils.isNull(value)) {
					// 超过长度缩小字体
					if (value.length() > maxLength) {
						view.setTextSize(dp2px(context, textSize));
					}
					setTextViewValue(view, value);
				} else {
					if (!StringUtils.isNull(defaultValue)) {
						// view.setText(defaultValue);
						setTextViewValue(view, defaultValue);
					} else {
						setTextViewValue(view, "");
					}

				}
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "setTextViewValue: ", e);

		}
	}

	public static void setTextViewValue(TextView textView, String value) {
		if (textView != null) {
			if (value == null) {
				value = "";
			}
			textView.setText(value);
			if (getChannelType() == 2) {
				textView.requestLayout();
			}
		}
	}

	// 判断路径是图片，还是颜色值
	public static boolean isImagePath(String relativePath) {
		if (!StringUtils.isNull(relativePath)) {
			relativePath = relativePath.toLowerCase();
			if (relativePath.endsWith("png") || relativePath.endsWith("jpg")) {
				return true;
			}
		}
		return false;

	}

	public static boolean isColorParam(String relativePath) {
		if (!StringUtils.isNull(relativePath)) {
			if (relativePath.indexOf(";") != -1) {
				return true;
			} else if (relativePath.indexOf("S#") != -1 || relativePath.indexOf("C#") != -1
					|| relativePath.indexOf("E#") != -1) {
				return true;
			}
		}
		return false;
	}

	public static boolean setImageSrc(Context context, ImageView imageView, String relativePath) throws Exception {
		return setImageSrc(context, imageView, relativePath, false);
	}

	public static boolean setImageSrc(Context context, ImageView imageView, String relativePath, boolean cache)
			throws Exception {
		Drawable dw = getDrawable(context, relativePath, true, cache);
		if (dw != null) {
			imageView.setImageDrawable(dw);
			return true;
		}
		return false;
	}

	/**
	 * 得到drawable
	 * 
	 * @param context
	 * @param relativePath
	 * @return
	 */
	public static Drawable getDrawable(Context context, String relativePath, boolean needColorDw, boolean cacheImg) {
		if (context == null)
			return null;
		Drawable resDraw = null;
		try {
			if (!StringUtils.isNull(relativePath)) {
				relativePath = relativePath.trim();
				if (ViewUtil.isImagePath(relativePath)) {
					if (cacheImg) {
						BitmapDrawable dr = ResourceCacheUtil.getImgDrawable(relativePath);
						// BitmapDrawable dr = imgCache.get(relativePath);
						if (dr != null && dr.getBitmap() != null && !dr.getBitmap().isRecycled()) {
							LogManager.d("drawable", "缓存中找到图片: ",relativePath);
							return dr;
						}
					}
					resDraw = createDrawableByPath(context, getCompletePath(relativePath));
					if (cacheImg && resDraw instanceof BitmapDrawable) {
						// imgCache.put(relativePath,(BitmapDrawable)resDraw);
						ResourceCacheUtil.putImgDrawable(relativePath, (BitmapDrawable) resDraw);
					}
				} else if (isColorParam(relativePath)) {
					if (cacheImg) {
						Drawable dr = ResourceCacheUtil.getColorDrawable(relativePath);
						// Drawable dr = colorDrawableCache.get(relativePath);
						if (dr != null) {
							LogManager.d("drawable", "2缓存中找到颜色图片: ", relativePath);
							return dr;
						}
					}
					ColorParam cp = ColorParam.parseColorParamStr(context, relativePath);
					resDraw = cp.getGDrawable();
					if (cacheImg && resDraw != null) {
						// colorDrawableCache.put(relativePath,resDraw);
						ResourceCacheUtil.putColorDrawable(relativePath, resDraw);
					}

				} else {
					if (needColorDw) {// 颜色drawable
						if (cacheImg) {
							Drawable dr = ResourceCacheUtil.getColorDrawable(relativePath);
							// Drawable dr =
							// colorDrawableCache.get(relativePath);
							if (dr != null) {
								LogManager.d("drawable", "1缓存中找到颜色图片: ",relativePath);
								return dr;
							}
						}
						int color = ResourceCacheUtil.parseColor(relativePath);
						resDraw = new ColorDrawable(color);
						if (cacheImg && resDraw != null) {
							// colorDrawableCache.put(relativePath,resDraw);
							ResourceCacheUtil.putColorDrawable(relativePath, resDraw);
						}
					}
				}
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "getDrawable: ", e);

		}
		return resDraw;
	}

	public static void setViewBg(Context context, View view, String relativePath) throws Exception {
		setViewBg(context, view, relativePath, false);
	}

	public static void setViewBg(Context context, View view, String relativePath, boolean cache) throws Exception {
		setBackground(view, getDrawable(context, relativePath, true, cache));

	}

	public static boolean setViewBg2(Context context, View view, String relativePath) throws Exception {
		if (context == null)
			return false;
		try {
			if (view != null && !StringUtils.isNull(relativePath)) {
				relativePath = relativePath.trim();
				if (ViewUtil.isImagePath(relativePath)) {
					Drawable drawable = ViewUtil.createDrawableByPath(context, ViewUtil.getCompletePath(relativePath));
					/* SDK-389 lianghailun 20160411 start */
					if (drawable == null) {
						return false;
					}
					/* SDK-389 lianghailun 20160411 end */
					view.setBackgroundDrawable(drawable);
					return true;
				} else if (isColorParam(relativePath)) {
					ColorParam cp = ColorParam.parseColorParamStr(context, relativePath);
					if (cp != null) {
						Drawable dw = cp.getGDrawable();
						if (dw != null) {
							view.setBackground(dw);
							return true;
						}
					}

				} else {
					try {
						int color = ResourceCacheUtil.parseColor(relativePath);
						view.setBackgroundColor(color);
						return true;
					} catch (Throwable e) {
						// TODO: handle Throwable
					}

				}
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "setViewBg2: ", e);

		}
		return false;

	}

	public static View createViewFromResource(Context context, int resid, ViewGroup root, boolean attachToRoot) {
		View resultView = null;

		try {

			LayoutInflater defalutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			resultView = defalutInflater.inflate(resid, root, attachToRoot);

		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "createViewFromResource: ", e);

		}
		return resultView;
	}

	public static Drawable createDrawableByPath(Context context, String imagePath, boolean isThrowException)
			throws Exception {
		try {

			if (StringUtils.isNull(imagePath))
				return null;

			if (imagePath.indexOf(".9.") != -1) {
				Bitmap bm = BitmapFactory.decodeFile(imagePath);

				if (bm != null) {

					bm.setDensity(getDensity(context));
					byte[] chunk = bm.getNinePatchChunk();
					if (!NinePatch.isNinePatchChunk(chunk))
						return null;
					NinePatchDrawable drawable = new NinePatchDrawable(context.getResources(), bm, chunk, new Rect(),
							null);
					return drawable;
				} else {
					if (isThrowException) {
						throw new Exception(imagePath);
					}

				}
			} else {
				Bitmap bm = BitmapFactory.decodeFile(imagePath);
				if (bm == null) {
					if (isThrowException) {

						throw new Exception(imagePath);
					}
					return null;
				}

				bm.setDensity(getDensity(context));
				Drawable dw = new BitmapDrawable(context.getResources(), bm);

				return dw;
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "createDrawableByPath: ", e);

			if (isThrowException) {
				throw new Exception(imagePath);
			}
		}
		return null;
	}

	public static String getCompletePath(String path) {
		return Constant.getDRAWBLE_PATH() + path;
	}

	public static Drawable createDrawableByPath(Context context, String imagePath) throws Exception {
		return createDrawableByPath(context, imagePath, true);
	}

	public static void recycle(Bitmap bitmap) {
		try {
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				bitmap = null;
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "recycle: ", e);

		}
	}

	public static void recycle(Drawable dw) {
		try {
			if (dw != null) {
				dw.setCallback(null);
				if (dw instanceof BitmapDrawable) {
					BitmapDrawable d = (BitmapDrawable) dw;
					recycle(d.getBitmap());
				} else if (dw instanceof NinePatchDrawable) {
					try {
						NinePatchDrawable nd = (NinePatchDrawable) dw;
						Field np = NinePatchDrawable.class.getDeclaredField("mNinePatch");
						if (np != null) {
							np.setAccessible(true);
							Object obj = np.get(nd);
							if (obj != null) {
								np = NinePatch.class.getDeclaredField("mBitmap");
								if (np != null) {
									np.setAccessible(true);
									Bitmap bm = (Bitmap) np.get(obj);
									if (bm != null) {
										recycle(bm);
									}
								}
							}
						}
					} catch (Throwable e) {
						// e.printStackTrace();
						LogManager.e(Constant.TAG, "recycle: ", e);

					}

				}
			}
			dw = null;
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "recycle: ", e);

		}
	}

	public static void recycleImageView(ImageView img) {
		try {
			if (img != null) {
				Drawable dw = img.getDrawable();
				img.setImageDrawable(null);
				recycle(dw);
				img = null;
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "recycleImageView: ", e);

		}
	}

	public static void recycleViewBg(View view) {
		try {
			if (view != null) {

				Drawable dw = view.getBackground();
				recycle(dw);

				view.setBackgroundDrawable(null);
				view = null;
			}
		} catch (Throwable e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "recycleViewBg: " , e);

		}
	}

	public static void setColor(View view, String color) {
		GradientDrawable myGrad = (GradientDrawable) view.getBackground();
		if (!StringUtils.isNull(color))
			myGrad.setColor(ResourceCacheUtil.parseColor(color));
	}

	static int density = -1;

	public static int getDensity(Context context) {
		if (density == -1) {

		    /* SDK-399 lianghailun 20160418 start*/
		    /* ASUS-1 huangzhiqiang 20160816 start */
            if (getChannelType() == 1 || getChannelType() == 2 || getChannelType() == 5 || getChannelType() == 8
                    || getChannelType() == 20 || getChannelType() == 22 || getChannelType() == 26
                    || getChannelType() == 28 || getChannelType() == 29) {
                density = context.getResources().getDisplayMetrics().DENSITY_XXHIGH;
            } else {
                density = context.getResources().getDisplayMetrics().DENSITY_HIGH;
            }
            /* ASUS-1 huangzhiqiang 20160816 end */
			/* SDK-399 lianghailun 20160418 end*/
//			/* SDK-390 lianghailun 20160413 start */
//			density = getDeviceDPI(context);
//			/* SDK-390 lianghailun 20160413 end */
		}
		// LogManager.d("ViewUtil",
		// "getDensity: "+density+" channel: "+KeyManager.channel);
		return density;
	}

//	/* SDK-390 lianghailun 20160413 start */
//	private static int getDeviceDPI(Context context) {
//		try {
//			float density = context.getResources().getDisplayMetrics().density;
//			LogManager.i(Constant.TAG,"method=getDeviceDPI:density = "+ density);
//			if (density >= 4.0) {
//				return DisplayMetrics.DENSITY_XXXHIGH;
//			}
//			if (density >= 3.0) {
//				return DisplayMetrics.DENSITY_XXHIGH;
//			}
//			if (density >= 2.0) {
//				return DisplayMetrics.DENSITY_XHIGH;
//			}
//			if (density >= 1.5) {
//				return DisplayMetrics.DENSITY_HIGH;
//			}
//			if (density >= 1.0) {
//				return DisplayMetrics.DENSITY_MEDIUM;
//			}
//		} catch (Throwable ab) {
//			LogManager.e(Constant.TAG,"method=getDeviceDPI"+ ab.getMessage(),ab);
//		}
//		return DisplayMetrics.DENSITY_LOW;
//	}
//
//	/* SDK-390 lianghailun 20160413 end */
	static int channelType = -1;

	/**
	 * 获取渠道类型
	 * 
	 * @return
	 */
	public static int getChannelType() {
		if (channelType == -1) {
			try {
				KeyManager.initAppKey();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
				LogManager.e(Constant.TAG, "getChannelType: ", e);

			}
			if ("NQIDAQABCOOL".equals(KeyManager.channel)) {
				// 酷派渠道
				channelType = 1;
			} else if ("1w36SBLwVNEW_ZTE".equals(KeyManager.channel)) {
				// 中兴新的方案渠道
				channelType = 2;
			} else if ("GwIDAQABZTE".equals(KeyManager.channel)) {
				// 中兴渠道
				channelType = 4;
			} else if ("VMhlWdEwVNEW_LENOVO".equals(KeyManager.channel)) {
				// 联想渠道类型
				channelType = 3;
			} else if ("Oq3iD6UlMAGIC".equals(KeyManager.channel)) {
				// 神奇工厂
				channelType = 5;
			} else if ("1i1BDH2wONE+".equals(KeyManager.channel) || "1i1BDH2wONE+CARD".equals(KeyManager.channel)) {
				// 1+
				channelType = 6;
			} else if ("3GdfMSKwHUAWEI".equals(KeyManager.channel)) {// huawei
				channelType = 7;
			} else if ("rq7Fyxl5DUOQU".equals(KeyManager.channel)) {
				// 多趣渠道
				channelType = 8;
			} else if ("j3FIT5mwLETV".equals(KeyManager.channel)) {
				// 乐视的方案渠道
				channelType = 9;
			} else if ("0GCSqGSITOS".equals(KeyManager.channel)) {
				// TOS的方案渠道
				channelType = 10;
			} else if ("D6mKXM8MEIZU".equals(KeyManager.channel)) {
				// 魅族方案渠道
				channelType = 11;
			} else if ("XRyvMvZwSMARTISAN".equals(KeyManager.channel)) {
				// 锤子方案渠道
				channelType = 2;
			} else if ("dToXA5JQDAKELE".equals(KeyManager.channel)) {
				// 大可乐方案渠道
				channelType = 2;
			} else if ("p5O4wKmwGIONEE".equals(KeyManager.channel)) {
				// 金立方案渠道，暂时和TOS一样
				channelType = 10;
			} else if ("z5N7W51wKINGSUN".equals(KeyManager.channel)) {
				// 广信方案渠道，暂时和奇酷一样
				channelType = 1;
			} else if ("Cko59T6wSUGAR".equals(KeyManager.channel)) {
				// sugar的方案渠道
				channelType = 12;
			} else if ("oWIH+3ZQLEIDIANOS".equals(KeyManager.channel)) {
				// leidianOS的方案渠道
				channelType = 12;
			} else if ("al30zFgQTEST_T".equals(KeyManager.channel)) {
				// 试接方案渠道，暂时和TOS一样
				channelType = 10;
			} else if ("gsjHPHwIKOOBEE".equals(KeyManager.channel)) {
				// 酷比的方案渠道
				channelType = 12;
			} else if ("QlTNSIgQWENTAI2".equals(KeyManager.channel)) {
				// 闻泰的方案渠道
				channelType = 12;
			} else if ("JqyMtaHQNUBIA".equals(KeyManager.channel)) {
				// nubia的方案渠道
				channelType = 12;
			} else if ("15Du354QGIONEECARD".equals(KeyManager.channel)) {
				// 金立卡夹的方案渠道
				channelType = 13;
			} else if ("rahtBH7wTCL".equals(KeyManager.channel)) {
				// 标准方案渠道
				channelType = 14;
			} else if ("xU6UT6pwTOS2".equals(KeyManager.channel)) {
				// 标准方案渠道
				channelType = 15;
			} else if ("5Gx84kmwYULONG_COOLPAD".equals(KeyManager.channel)) {
				// 标准方案渠道
				channelType = 16;
			} else if ("tnjdWFeQKTOUCH".equals(KeyManager.channel)) {
				// 天语方案渠道
				channelType = 19;
			} else if ("Uj2pznXQHCT".equals(KeyManager.channel)) {
				// 豪成方案渠道
				channelType = 12;
			} else if ("XkXZJmwIPPTV".equals(KeyManager.channel)) {
				// PPTV方案渠道
				channelType = 12;
			} else if ("dGxSiEbwTOSCARD".equals(KeyManager.channel)) {
				// tos card
				channelType = 17;
			} else if ("PzqP0ONQTOSWATCH".equals(KeyManager.channel)) {
				// tos watch
				channelType = 18;
			} else if ("VCTyBOSwSmartisan".equals(KeyManager.channel)) {
				// 锤子手机
				channelType = 18;
			} else if ("5rLWVKgQMEITU_PHONE".equals(KeyManager.channel)) {
				// 美图方案渠道
				channelType = 12;
			} else if ("zcK2P6yQINNOS".equals(KeyManager.channel)) {
				// innos方案渠道
				channelType = 12;
			} else if ("RbWRsTYQdroi".equals(KeyManager.channel)) {
				// 卓易方案渠道
				channelType = 12;
			} else if ("J2kSrxdQGigaset".equals(KeyManager.channel)) {
				// Gigaset 方案渠道
				channelType = 12;
			} else if ("5zZZdrFQIUNI".equals(KeyManager.channel)) {
				// IUNI 方案渠道
				channelType = 12;
			} else if ("nZpg6u3wDOOV".equals(KeyManager.channel)) {
				// DOOV 方案渠道
				channelType = 12;
			} else if ("NsJCCyFwPHILIPS".equals(KeyManager.channel)) {
				// 飞利浦 方案渠道（试接）
				channelType = 12;
			} else if ("UdcqV6aQLANMO".equals(KeyManager.channel)) {
				// 蓝魔方案渠道
				channelType = 12;
			} else if ("PunKwZfwHISENSE".equals(KeyManager.channel)) {
				// 海信方案渠道
				channelType = 12;
			} else if ("gO0o2CXwVIVO".equals(KeyManager.channel)) {
				// VIVO方案渠道（试接）
				channelType = 12;
			} else if ("K8wgPuIwFREEMEOS".equals(KeyManager.channel)) {
				// 卓易方案渠道
				channelType = 12;
			} else if ("DAS9exiQQIKUBOX".equals(KeyManager.channel)) {
				// 奇酷消息盒子
				channelType = 20;
			}
			/* SDK-390 lianghailun 20160413 start */
			else if ("d7tjnrkwCNSAMSUNG".equals(KeyManager.channel)) {
				// 三星渠道
				channelType = 22;
			}/* SDK-390 lianghailun 20160413 end */
	        /* SDK-427 jinzhengbin 20160509 start */
			else if ("uDM3hYtwGIGASET".equals(KeyManager.channel)) {
                // 集怡嘉
                channelType = 12;
            }/* SDK-427 jinzhengbin 20160509 start */
			/* SDK-461 jinzhengbin 20160526 start */
            else if ("OmwdltCwONEPLUS2".equals(KeyManager.channel)) {
                //一加2
                channelType = 23;
            }/* SDK-461 jinzhengbin 20160526 start */
			/* SDK-488 jinzhengbin 20160616 start */
            else if ("mmNPM4cQVNEW_ZTE2".equals(KeyManager.channel)) {
                channelType = 24;
            }else if ("ZkhM4GyQ360OS".equals(KeyManager.channel)) {
                channelType = 25;
            }
			/* SDK-488 jinzhengbin 20160616 start */
            else if ("7N4EhHawHUAWEI2".equals(KeyManager.channel)) {
		     //huawei 2
                channelType = 26;
            }
            else if ("vRICR8qQYULONG_COOLPAD2".equals(KeyManager.channel)) {
                channelType = 27;
            }
            /* ASUS-1 huangzhiqiang 20160816 start */
            else if ("i3GPvZLwASUS".equals(KeyManager.channel)) {
                // 华硕 方案渠道
                channelType = 28;
            }
            /* ASUS-1 huangzhiqiang 20160816 end */
            else if ("cNNrw5WQEBEN".equals(KeyManager.channel)) {
                // E人E本方案渠道
                channelType = 29;
            }else if ("XHpWJNFQTCLOS".equals(KeyManager.channel)) {
                // TCLOS方案渠道
                channelType = 12;
            }else if ("R1pU1XXwUNISCOPE".equals(KeyManager.channel)) {
                // 优思方案渠道
                channelType = 12;
            }else if ("gOLrCBhQMEIZU2".equals(KeyManager.channel)) {
                // 魅族方案渠道
                channelType = 11;
            }
            /* UIX-229 jinzhengbin 20161012 start */
            else if ("MkekV0RQRAGENTEK".equals(KeyManager.channel)) {
                //锐嘉科渠道
                channelType = 12;
            }
            /* UIX-229 jinzhengbin 20161012 end */
	    	/* QIKBOX-145 jinzhengbin 20161101 start */
            else if ("YVmD5UkQ360OSBOX".equals(KeyManager.channel)) {
                //360OSBOX渠道
                channelType = 20;
            }
			/* QIKBOX-145 jinzhengbin 20161101 end */
            else if ("2qqJKJbwZTE_TRIP".equals(KeyManager.channel)) {
                //中兴智能出行
                channelType = 20;
            }
            else if ("n2zkSOdwZTE3".equals(KeyManager.channel)) {
                channelType = 24;
            }
            else if ("XHFBWgoQHUAWEI3".equals(KeyManager.channel)) {
   		     //huawei6.0
                   channelType = 26;
            }
            else if ("xvioMB1wDAMI".equals(KeyManager.channel)) {
      		     //大米
                      channelType = 12;
               }
            else if ("XHXXOaoQGOME".equals(KeyManager.channel)) {
     		     //国美
                     channelType = 12;
              }
            else if ("Chzck7+wIVVI".equals(KeyManager.channel)) {
                channelType = 27;
            }
            else if ("qV7LzWUQMEIZUMAP".equals(KeyManager.channel)) {
                // 魅族方案渠道
                channelType = 11;
            }
            else if ("YEdFWwxwHALOVE".equals(KeyManager.channel)) {
    		     //九爱
                    channelType = 12;
             }
            else {
				channelType = 0;
			}
		}
		return channelType;
	}

	public static void setBackground(View target, Drawable drawable) {
		if (target == null)
			return;
		if (VERSION.SDK_INT > 16) {
			target.setBackground(drawable);
		} else {
			target.setBackgroundDrawable(drawable);
		}
	}

	/**
	 * dp转换为px
	 * 
	 * @param context
	 * @param dpVal
	 * @return
	 */
	public static int dp2px(Context context, int dpVal) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal,
				context.getResources().getDisplayMetrics());
	}

	public static Bitmap createRepeaterX(int count, Bitmap src) {
		// int count = (width + src.getWidth() - 1) / src.getWidth(); //
		// 计算出平铺填满所给width（宽度）最少需要的重复次数

		Bitmap bitmap = Bitmap.createBitmap(src.getWidth() * count, src.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		for (int idx = 0; idx < count; ++idx) {
			canvas.drawBitmap(src, idx * src.getWidth(), 0, null);
		}
		return bitmap;
	}

	public static View createView(Context context, int id) {
		View view = new View(context);
		view.setId(id);
		return view;

	}

	/**
	 * 依据图片文件名,创建图片
	 * 
	 * @param imgPath
	 * @param width
	 * @param height
	 * @return
	 */
	public static BitmapDrawable createBitmapByPath(Context context, String imgPath, int width, int height) {
		try {
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(imgPath, opt);

			int w = opt.outWidth;
			int h = opt.outHeight;
			opt.inDensity = w;
			opt.inTargetDensity = width;
			opt.inJustDecodeBounds = false;
			// opt.inScaled =true;
			// opt.inSampleSize = w/width;
			Bitmap bit = BitmapFactory.decodeFile(imgPath, opt);
			bit.setDensity(w);
			BitmapDrawable dr = new BitmapDrawable(context.getResources(), bit);
			return dr;
		} catch (Throwable e) {
			// TODO: handle Throwable
		}
		return null;

	}

	private static final Charset UTF_8 = Charset.forName("UTF-8");

	private static String inputStreamToString(InputStream in) throws IOException {
		return readFully(new InputStreamReader(in, UTF_8));
	}

	public static String readFully(Reader reader) throws IOException {
		try {
			StringWriter writer = new StringWriter();
			char[] buffer = new char[1024];
			int count;
			while ((count = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, count);
			}
			return writer.toString();
		} finally {
			reader.close();
		}
	}

	public static synchronized BitmapDrawable createBitmapByPath2(Context context, String imgPath, int width,
			int height) {
		return createBitmapByPath2(context, new File(imgPath), width, height);
	}

	public static BitmapDrawable createBitmapByPath2(Context context, File imgPathFile, int width, int height) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(imgPathFile);
			FileDescriptor fileDescriptor = fileInputStream.getFD();

			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
			int w = options.outWidth;
			// int h = options.outHeight;
			options.inDensity = w;
			options.inTargetDensity = width;
			options.inJustDecodeBounds = false;

			Bitmap bit = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
			bit.setDensity(w);
			BitmapDrawable dr = new BitmapDrawable(context.getResources(), bit);
			return dr;

		} catch (Throwable e) {
			// TODO: handle Throwable
		} finally {
			FileUtils.close(fileInputStream);
		}
		return null;

	}

	/**
	 * 获取尺寸值
	 * 
	 * @param dimenId
	 * @return
	 */
	public static float getDimension(int dimenId) {
		try {
			return Constant.getContext().getResources().getDimension(dimenId);
		} catch (NotFoundException e) {
			// e.printStackTrace();
			LogManager.e(Constant.TAG, "getDimension: ", e);

		}
		return 0;
	}

    /* SDK-570 huangzhiqiang 20160802 start */
    public static String getXCode4() {
        return "3531344537383645";
    }
    /* SDK-570 huangzhiqiang 20160802 end */

    public static CharSequence formatSpanString(CharSequence text, JSONObject dataObject, Map<String, String> extend) {
        /* SDK-558 huangzhiqiang 20160725 start */
     if (text == null || dataObject == null) {
         return null;
     }
        /* SDK-558 huangzhiqiang 20160725 end */
     try {
         JSONArray jArray = dataObject.optJSONArray("items");
         if (jArray == null || jArray.length() < 1) {
             return null;
         }
         String optSign = dataObject.optString("sign");
         if (!TextUtils.isEmpty(optSign) && extend != null) {
             extend.put("sign", optSign);
         }
            /* SDK-623 20160922 zhaojiangwei start */
         SpannableStringBuilder spanStr = new SpannableStringBuilder(text);
            /* SDK-623 20160922 zhaojiangwei end */

            /*SDK-605 hewengao/20161003 start*/
         String msgId = null;
         int normal_color =0;
         int pressed_color =0;
         boolean underLine =false;
         if (extend != null) {
                /*SDK-635 songzhirong 20161009 start*/
             msgId = String.valueOf(extend.get("msgId"));
                /*SDK-635 songzhirong 20161009 end*/

             if (extend.containsKey("normal_color")) {
                 try {
                     normal_color = Integer.valueOf(extend.get("normal_color"));
                 } catch (Throwable e) {
                     LogManager.e("XIAOYUAN", "formatSpanString style normal_color config error");
                 }
             }
             if (extend.containsKey("pressed_color")) {
                 try {
                     pressed_color = Integer.valueOf(extend.get("pressed_color"));
                 } catch (Throwable e) {
                     LogManager.e("XIAOYUAN", "formatSpanString pressed_color style config error");
                 }
             }
                /*SDK-605 hewengao/20161003 start*/
             if (extend.containsKey("selected_bg_color")) {
                 try{
                     BgSpan.setBgColor(Integer.valueOf(extend.get("selected_bg_color")));
                 }catch(Throwable e){
                     LogManager.e(Constant.TAG, "BgSpan.setBgColor error",e);
                 }
             }
                /*SDK-605 hewengao/20161003 end*/
                /*SDK-587 zhaojiangwei 20160812 start*/
             if (extend.containsKey("under_line")) {
                 try{
                     underLine = Boolean.parseBoolean(extend.get("under_line"));
                 }catch(Throwable e){
                     LogManager.e(Constant.TAG, "BgSpan.parseBoolean under_line error",e);
                 }
             }
             /*SDK-587 zhaojiangwei 20160812 end*/
         }
         /*SDK-605 hewengao/20161003 end*/
         JSONObject jobj = null;
         for (int i = 0; i < jArray.length(); i++) {
             jobj = jArray.optJSONObject(i);
             if(msgId != null){
                 jobj.put("msgId", msgId);
             }
             int start = Integer.valueOf((String) jobj.get("startIndex"));
             int end = Integer.valueOf((String) jobj.get("endIndex"));
                /*SDK-409 hewengao 20160426 start*/
             TouchableSpan touch = new TouchableSpan(jobj, extend);
                /*SDK-409 hewengao 20160426 end*/
             touch.setStyle(normal_color,pressed_color);
             touch.setShowUnderLine(underLine);
             spanStr.setSpan(touch, start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
         }

         return spanStr;
     } catch (Throwable e) {
         LogManager.e("XIAOYUAN", "formatSpanString error:", e);
     }
     return null;
 }
    /* SDK-383 特征值识别接口  xusongzhou 20160412 end */

    /* SDK-383 特征值格式化  xusongzhou 20160412 start */
    public static boolean formatSpanString(TextView tv, CharSequence text, JSONObject dataObject, Map<String, String> extend) {
        /* SDK-558 huangzhiqiang 20160725 start */
        if (tv == null || text == null || dataObject == null) {
            return false;
        }
        /* SDK-558 huangzhiqiang 20160725 end */
        try {
            JSONArray jArray = dataObject.optJSONArray("items");
            if (jArray == null || jArray.length() < 1) {
                return false;
            }
            String optSign = dataObject.optString("sign");
            if (!TextUtils.isEmpty(optSign) && extend != null) {
                extend.put("sign", optSign);
            }
            /* SDK-623 20160922 zhaojiangwei start */
            SpannableStringBuilder spanStr = new SpannableStringBuilder(text);
            /* SDK-623 20160922 zhaojiangwei end */
            
            /*SDK-605 hewengao/20161003 start*/
            String msgId = null;
            int normal_color =0;
            int pressed_color =0;
            boolean underLine =false;
            boolean distributeTouch = true;
            if (extend != null) {
                /*SDK-635 songzhirong 20161009 start*/
                msgId = String.valueOf(extend.get("msgId"));
                /*SDK-635 songzhirong 20161009 end*/

                if (extend.containsKey("normal_color")) {
                    try {
                        normal_color = Integer.valueOf(extend.get("normal_color"));
                    } catch (Throwable e) {
                        LogManager.e("XIAOYUAN", "formatSpanString style normal_color config error");
                    }
                }
                if (extend.containsKey("pressed_color")) {
                    try {
                        pressed_color = Integer.valueOf(extend.get("pressed_color"));
                    } catch (Throwable e) {
                        LogManager.e("XIAOYUAN", "formatSpanString pressed_color style config error");
                    }
                }
                /*SDK-605 hewengao/20161003 start*/
                if (extend.containsKey("selected_bg_color")) {
                    try{
                        BgSpan.setBgColor(Integer.valueOf(extend.get("selected_bg_color")));
                    }catch(Throwable e){
                        LogManager.e(Constant.TAG, "BgSpan.setBgColor error",e);
                    }
                }
                /*SDK-605 hewengao/20161003 end*/
                /*SDK-587 zhaojiangwei 20160812 start*/
                if (extend.containsKey("under_line")) {
                    try{
                      underLine = Boolean.parseBoolean(extend.get("under_line"));
                    }catch(Throwable e){
                        LogManager.e(Constant.TAG, "BgSpan.parseBoolean under_line error",e);
                    }
                }
                /*SDK-587 zhaojiangwei 20160812 end*/
                /*SDK-737 zhaojiangwei/20170321 start*/
                if (extend.containsKey("distribute_touch")) {
                    try{
                        distributeTouch = Boolean.parseBoolean(extend.get("distribute_touch"));
                      }catch(Throwable e){
                          LogManager.e(Constant.TAG, "BgSpan.parseBoolean distribute_touch error",e);
                      }
                }
                /*SDK-737 zhaojiangwei/20170321 end*/
            }
            /*SDK-605 hewengao/20161003 end*/
            JSONObject jobj = null;
            for (int i = 0; i < jArray.length(); i++) {
                jobj = jArray.optJSONObject(i);
                if(msgId != null){
                    jobj.put("msgId", msgId);
                }
                int start = Integer.valueOf((String) jobj.get("startIndex"));
                int end = Integer.valueOf((String) jobj.get("endIndex"));
                /*SDK-409 hewengao 20160426 start*/
                TouchableSpan touch = new TouchableSpan(jobj, extend);
                /*SDK-409 hewengao 20160426 end*/
                touch.setStyle(normal_color,pressed_color);
                touch.setShowUnderLine(underLine);
                spanStr.setSpan(touch, start, end, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            tv.setText(spanStr);
            tv.setMovementMethod(LinkTouchMovementMethod.getLinkTouchInstance(distributeTouch));
            return true;
        } catch (Throwable e) {
            LogManager.e("XIAOYUAN", "formatSpanString error:", e);
        }
        return false;
    }
    /* SDK-383 特征值识别接口  xusongzhou 20160412 end */
    
    /*SDK-605 hewengao/20161003 start*/
    public static void clearSpan(){
        try {
            ((LinkTouchMovementMethod) LinkTouchMovementMethod.getLinkTouchInstance()).clear();
        }catch (Throwable e){
            LogManager.e("XIAOYUAN", "ViewUtil.clearSpan error:", e);
        }

    }
    /*SDK-605 hewengao/20161003 end*/
}
